package jjn.round1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jjn
 * @since 2022-08-01 9:46
 */
public class LeetCode54_SpiralMatrix {
    
    public List<Integer> spiralOrder(int[][] matrix) {
        int height = matrix.length;
        int width = matrix[0].length;
        int maxSize = width * height;
        List<Integer> result = new ArrayList<>(maxSize * 2);
        int left = 0, right = width - 1;
        int top = 0, bottom = height - 1;
        while (left <= right) {
            while (top <= bottom) {
                // 从左访问到右, 纵坐标是top
                for (int i = left; i <= right; i++) {
                    boolean shouldBreak = checkAddOrBreak(matrix[top][i], result, maxSize);
                    if (shouldBreak) {
                        return result;
                    }
                }
                top++;
                // 从上访问到下, 横坐标是right
                for (int i = top; i <= bottom; i++) {
                    boolean shouldBreak = checkAddOrBreak(matrix[i][right], result, maxSize);
                    if (shouldBreak) {
                        return result;
                    }
                }
                right--;
                // 从右访问到左, 纵坐标是bottom
                for (int i = right; i >= left; i--) {
                    boolean shouldBreak = checkAddOrBreak(matrix[bottom][i], result, maxSize);
                    if (shouldBreak) {
                        return result;
                    }
                }
                bottom--;
                // 从下访问到上, 横坐标是left
                for (int i = bottom; i >= top; i--) {
                    boolean shouldBreak = checkAddOrBreak(matrix[i][left], result, maxSize);
                    if (shouldBreak) {
                        return result;
                    }
                }
                left++;
            }
        }
        return result;
    }
    
    private boolean checkAddOrBreak(int element, List<Integer> result, int maxSize) {
        result.add(element);
        return result.size() >= maxSize;
    }
}
